package gosend

import (
	"strconv"
	"strings"
	"time"

	"gorm.io/gorm"
)

// GoSendNotify GoSend物流状态更新通知，详情见https://ecommercetools-integration.gojek.co.id/
type GoSendNotify struct {
	Id                 int64  `json:"id" gorm:"primary_key;auto_increment"`
	EntityId           string `json:"entity_id"`
	Type               string `json:"type"`
	EventDate          string `json:"event_date"`
	EventId            string `json:"event_id"`
	PartnerId          string `json:"partner_id"`
	BookingId          string `json:"booking_id"` // 物流单号 同delivery.number
	Status             string `json:"status"`
	BookingType        string `json:"booking_type"` // 物流类型 Instant、SameDay
	DriverName         string `json:"driver_name"`
	DriverPhone        string `json:"driver_phone"`
	DriverPhone2       string `json:"driver_phone2"`
	DriverPhone3       string `json:"driver_phone3"`
	DriverPhotoUrl     string `json:"driver_photo_url"`
	ReceiverName       string `json:"receiver_name"`
	TotalDistanceInKms string `json:"total_distance_in_kms"`
	PickupEta          string `json:"pickup_eta"`   // 预计取件时间范围 格式"1486528706000-1486528707000"（时间戳）
	DeliveryEta        string `json:"delivery_eta"` // 预计送达时间范围 格式"1486528708000-1486528709000"（时间戳）
	Price              string `json:"price"`
	CancelledBy        string `json:"cancelled_by"`
	CancellationReason string `json:"cancellation_reason"`
	LiveTrackingUrl    string `json:"live_tracking_url"` // gosend官方轨迹跟踪url

	PickupTimeStart   time.Time `json:"pickup_time_start"`
	PickupTimeEnd     time.Time `json:"pickup_time_end"`
	DeliveryTimeStart time.Time `json:"delivery_time_start"`
	DeliveryTimeEnd   time.Time `json:"delivery_time_end"`
	CreateTime        time.Time `json:"create_time"`
}

func (GoSendNotify) TableName() string {
	return "gosend_notify"
}

func (item *GoSendNotify) BeforeCreate(tx *gorm.DB) error {
	if len(item.PickupEta) > 0 {
		a := strings.Split(item.PickupEta, "-")
		if len(a) == 2 {
			start, _ := strconv.ParseInt(a[0], 10, 64)
			end, _ := strconv.ParseInt(a[1], 10, 64)
			start = start / 1000
			end = end / 1000
			item.PickupTimeStart = time.Unix(start, 0)
			item.PickupTimeEnd = time.Unix(end, 0)
		}
	}
	if len(item.DeliveryEta) > 0 {
		a := strings.Split(item.DeliveryEta, "-")
		if len(a) == 2 {
			start, _ := strconv.ParseInt(a[0], 10, 64)
			end, _ := strconv.ParseInt(a[1], 10, 64)
			start = start / 1000
			end = end / 1000
			item.DeliveryTimeStart = time.Unix(start, 0)
			item.DeliveryTimeEnd = time.Unix(end, 0)
		}
	}

	var now = time.Now()
	item.CreateTime = now
	return nil
}
